'use strict'

import React, { Component } from 'react';

import {
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    AsyncStorage,
    ScrollView
} from 'react-native';

import {NavBarBackItem, NavBarTitleItem, NavBarRightItem} from './NavbBarItems';
import NavigatorBarView from './NavigatorBarView';
import Calendar from './Calendar';
import NotifyActions from '../actions/NotifyActions';
import InteractionManager from 'InteractionManager';
import ListMenuBar from './ListMenuBar';
import DCAction from '../actions/DCAction';
import dcalt from '../alt/DCAlt'
import DCStore from '../stores/DCStore'
import LoadingFailView from '../config/LoadingFailView'


var mon = new Date().getMonth()+1
var time = new Date().getFullYear()+'/'+mon+'/'+new Date().getDate()+' 8:00:00';
var gMyTime = new Date(time).getTime();


export default class DCView extends Component {
    constructor(props){
        super();
        this.state={
             menuItems: Immutable.fromJS([
                {'id': 'filter', 'name': '午餐', 'dinner': 'lunch'},
                {'id': 'filter', 'name': '晚餐', 'dinner': 'supper'}]),   
             isSelect: 0,
             username: undefined,
             name: undefined,
             numLunch: [],
             numSupper: [],
             lObjId: undefined,
             sObjId: undefined,
             dcUsersLNum: [],
             dcUsersSNum: [],
             showView: true,
             disabled: false,
        };
    };
    //选择 午餐/晚餐(菜单点击回调)
    selectAction = (index)=> {
        if (index != this.state.isSelect) {
            this.setState({isSelect: index});
        };
    };
    onChange = ()=> {
        this.state.username = ALT.stores.DCStore.getState().username//用户名
        this.state.name = ALT.stores.DCStore.getState().name//用户姓名
        this.state.numLunch = ALT.stores.DCStore.getState().numLunch//本月点击午餐的数组
        this.state.numSupper = ALT.stores.DCStore.getState().numSupper//本月点击晚餐的数组
        this.state.lObjId = ALT.stores.DCStore.getState().lObjId//午餐的id
        this.state.sObjId = ALT.stores.DCStore.getState().sObjId//晚餐的id
        this.state.dcUsersLNum = ALT.stores.DCStore.getState().dcUsersLNum//本日累计点午餐人数
        this.state.dcUsersSNum = ALT.stores.DCStore.getState().dcUsersSNum//本日累计点晚餐人数

        this.setState({disabled: ALT.stores.DCStore.getState().disabled})
    };
    //加载失败
    loadingFail = ()=> {
        this.setState({showView: false})
    };
    componentDidMount() {         
        InteractionManager.runAfterInteractions(()=>{
            ALT.actions.DCAction.queryDCObj()
            ALT.actions.DCAction.queryTodayObj()
        });
        ALT.stores.DCStore.listen(this.onChange);

        NotifyActions.addNotifier('LoadingFailHome', this.loadingFail, this);
    };
    componentWillUnmount() {
        ALT.stores.DCStore.unlisten(this.onChange);
        NotifyActions.removeNotifier('LoadingFailHome', this.loadingFail, this);
    };

    render(){
        var dinner;
        var todayNum;

        if (this.state.showView == false) {
            dinner =  (<LoadingFailView/>);
        }else{
            if (this.state.isSelect == 0) {
                dinner = (<View>
                            <DCButton isSelect = {this.state.isSelect}
                                    username = {this.state.username}
                                    name = {this.state.name}
                                    numLunch = {this.state.numLunch}
                                    lObjId = {this.state.lObjId}
                                    dd = {this.state.disabled}/>

                            <Calendar signDates = {this.state.numLunch}/>
                            <Text style={styles.dcCountTitle}>本月累计点午餐: {this.state.numLunch.length}</Text>
                                                  
                          </View>);
                todayNum = (<Text style={styles.dcCountCook}>本日累计点午餐人数: {this.state.dcUsersLNum.length}</Text>);
            }else{
                dinner = (<View>
                            <DCButton isSelect = {this.state.isSelect}
                                    username = {this.state.username}
                                    name = {this.state.name}
                                    numSupper = {this.state.numSupper}
                                    sObjId = {this.state.sObjId}
                                    dd = {this.state.disabled}/>

                            <Calendar signDates = {this.state.numSupper}/>
                            <Text style={styles.dcCountTitle}>本月累计点晚餐: {this.state.numSupper.length}</Text>
                                                   
                          </View>);
                todayNum = (<Text style={styles.dcCountCook}>本日累计点晚餐人数: {this.state.dcUsersSNum.length}</Text>);
            }
        }
            
        return(
            <View style = {{width: Common.size.width,height: Common.size.height, flex: 1,backgroundColor: 'white'}}>
                <NavigatorBarView
                    centerItem={<NavBarTitleItem
                        title="点餐"/>}
                    rightItem = {<NavBarRightItem/>}/>
                <ListMenuBar
                    key='ListMenuBar'
                    ref='ListMenuBar'
                    titleKey={'name'}
                    menuItems={this.state.menuItems}
                    menuCallBackAction={this.selectAction}/>
                <ScrollView automaticallyAdjustContentInsets={false}>
                    {dinner}

                    <Text style={styles.dcCountTitle}>
                        合计: {this.state.numLunch.length+this.state.numSupper.length}
                    </Text>

                    {todayNum}
                </ScrollView>
            </View>
        )
    }
    

}
//点餐按钮
class DCButton extends Component {
    constructor(props){
        super();
        this.state={             
             type: [],
             lState: true,
             sState: true,

             isChoose:false,
        };
    };

   //是否点午餐
    lunchAction = ()=> {
        var nowTime = this.getTime()
        var newDay = Immutable.fromJS({type: "0",
                                       username: this.props.username,
                                       name: this.props.name,
                                       time: nowTime
                                       })
        this.state.type =  JSON.stringify(newDay)

        ALT.actions.DCAction.addObj(this.state.type)  

    };
    //是否点晚餐
    supperAction = ()=> {
        var nowTime = this.getTime()
        var newDay = Immutable.fromJS({type:"1",
                                       username: this.props.username,
                                       name: this.props.name,
                                       time: nowTime
                                       })
        this.state.type = JSON.stringify(newDay)
        ALT.actions.DCAction.addObj(this.state.type)   

    };
    //判断是否点餐成功
    dcSucess = (objID)=> {
        if (objID) {
            if (this.props.isSelect == 0) {
                this.setState({lState: false});
            }else{
                this.setState({sState: false});
            }
            ALT.actions.DCAction.queryDCObj()
            ALT.actions.DCAction.queryTodayObj()
        };
    };
    //取消点餐
    delAction = ()=> {
        if (this.props.isSelect == 0) {
            var obj = Immutable.fromJS({type:"0",
                                       objId: this.props.lObjId,
                                       })
            ALT.actions.DCAction.delObj(obj)
        }else{
            var obj = Immutable.fromJS({type:"1",
                                       objId: this.props.sObjId,
                                       })
            ALT.actions.DCAction.delObj(obj)
        }
        
    };
    //判断是否取消点餐成功
    delSucess = (result)=> {
        if (result) {
            if (this.props.isSelect == 0) {
                this.setState({lState: true});
            }else{
                this.setState({sState: true});
            }
            ALT.actions.DCAction.queryDCObj()
            ALT.actions.DCAction.queryTodayObj()
        };
    };
    getTime=()=> {
        var mon = new Date().getMonth()+1
        var time = new Date().getFullYear()+'/'+mon+'/'+new Date().getDate()
                    +' '+new Date().getHours()+':'+new Date().getMinutes()+':'+new Date().getSeconds();
        var timeStamp = new Date(time).getTime();
        var nowTime;
        if (timeStamp > gMyTime) {
            timeStamp = timeStamp+86400000   //+1天         
        };
        var   d=new   Date(timeStamp);                 
        var a = this.formatDate(d); 
        
        return a;
    }
    formatDate=(now)=> {     
       var year=now.getFullYear();     
       var month=now.getMonth()+1;
       if (month < 10) {
           month='0'+month;
       };     
       var day=now.getDate();
       if (day < 10) {
           day='0'+day
       };     
       var hour=now.getHours();
       if (hour < 10) {
           hour='0'+hour
       };       
       var minute=now.getMinutes();
       if (minute < 10) {
           minute='0'+minute
       };     
       var second=now.getSeconds();
       if (second < 10) {
           second='0'+second
       };     
       return   year+"/"+month+"/"+day+" "+hour+":"+minute+":"+second;          
    }     
    
    componentDidMount() {  
        NotifyActions.addNotifier('dcSucess', this.dcSucess, this);
        NotifyActions.addNotifier('delSucess', this.delSucess, this);
    };
    componentWillUnmount() {
        NotifyActions.removeNotifier('dcSucess', this.dcSucess, this);
        NotifyActions.removeNotifier('delSucess', this.delSucess, this);
    };
    render(){
        var dcButtonStyle = [styles.dcButton];
        var dcButtonTitle;

        var nowTime = this.getTime().toString().substring(8,10)
       //判断是否已经点餐（改变按钮状态）
            if (this.props.isSelect == 0) {
                if (this.state.lState == true && this.props.numLunch[this.props.numLunch.length-1]!=nowTime) { 
                    dcButtonStyle.push({backgroundColor: '#7fff00'});
                    dcButtonTitle = '点餐';

                }else{
                    dcButtonStyle.push({backgroundColor: 'red'});
                    dcButtonTitle = '取消点餐';
                }
            }else{
                if (this.state.sState == true && this.props.numSupper[this.props.numSupper.length-1]!=nowTime) {                  
                    dcButtonStyle.push({backgroundColor: '#7fff00'});
                    dcButtonTitle = '点餐';
                }else{
                    dcButtonStyle.push({backgroundColor: 'red'});
                    dcButtonTitle = '取消点餐';
                }
            }


           
        return(
            <View style={styles.dcHeader}>
                <TouchableOpacity
                        style={dcButtonStyle}
                        onPress={()=>{
                            if (this.props.dd) {
                                return
                            }
   
                            if (this.props.isSelect == 0) {
                                if (this.props.numLunch[this.props.numLunch.length-1]!=nowTime) {
                                    this.lunchAction()
                                }else if (this.props.numLunch[this.props.numLunch.length-1]==nowTime) {
                                    this.delAction()
                                }
                            }else{
                               if(this.props.numSupper[this.props.numSupper.length-1]!=nowTime){
                                  this.supperAction()
                               }else if (this.props.numSupper[this.props.numSupper.length-1]==nowTime) {
                                  this.delAction()
                               } 
                            }
                        }}>
                    <Text style={{color: 'white', fontSize: asFont(16)}}>{dcButtonTitle}</Text>
                </TouchableOpacity>
            </View>
        );
    }
}



var styles = StyleSheet.create({
    dcHeader: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        alignItems: 'center',
        height: as(90),
        padding: as(10),
        borderBottomColor: '#ccc',
        borderBottomWidth: as(0.5)
    },
    btn: {
        height: as(45),
        borderWidth: as(2),
        justifyContent: 'center',
        alignItems: 'center',
    },
    selectTime: {
        width: Common.size.width/2-as(4),
        fontSize: asFont(16),
        color: 'gray',
        textAlign: 'center'
    },
    dcButton: {
        height: as(70),
        width: as(70),
        borderRadius: as(35),
        backgroundColor: 'rgb(74, 168, 215)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    dcCountTitle: {
        marginLeft: as(10),
        marginBottom: as(10),
        fontSize: asFont(15),
        color: 'gray'
    },
    dcCountCook: {
        marginLeft: as(10),
        marginBottom: as(10),
        fontSize: asFont(15),
        color: 'red'
    },

})



